﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Messaging;

namespace FeCMS.AccessControlModule.ContextAccess
{
    /// <summary>
    ///     权限消息接收器接口
    /// </summary>
    public class PermissionSink : IMessageSink 
    {
        /// <summary>
        ///     保存下一个接收器
        /// </summary>
        private IMessageSink nextSink;

        /// <summary>
        ///     在构造器中初始化下一个接收器
        /// </summary>
        /// <param name="next"></param>
        public PermissionSink(IMessageSink next)
        {
            nextSink = next;
        }

        #region IMessageSink 成员

        /// <summary>
        ///     异步处理消息【暂不处理】
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="replySink"></param>
        /// <returns></returns>
        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            return null;
        }

        /// <summary>
        ///     消息属性接口
        /// </summary>
        public IMessageSink NextSink
        {
            get { return nextSink; }
        }

        /// <summary>
        ///     当消息传递的时候，该方法被调用
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IMessage SyncProcessMessage(IMessage msg)
        {
            //拦截消息，做前处理
            Preprocess(msg);
            //传递消息给下一个接收器
            IMessage retMsg = nextSink.SyncProcessMessage(msg);
            //调用返回时进行拦截，并进行后处理


            return retMsg;
        }

        #endregion

        /// <summary>
        ///     处理
        /// </summary>
        /// <param name="msg"></param>
        private void Preprocess(IMessage msg)
        {
            IMethodCallMessage call = msg as IMethodCallMessage;
            if (call == null)
                return;

            var mustPowers = call.MethodBase.GetCustomAttributes(typeof(PermissionAttribute), false) as PermissionAttribute[];


            if (mustPowers == null || mustPowers.Length==0)
            {
                return;
            }

            foreach (PermissionAttribute mustPower in mustPowers)
            {
                if (!mustPower.ValidPermission())
                {
                    throw new Exception("没权限");
                }
            }

        }

    }
}
